package dp;


import java.util.Arrays;
import java.util.Comparator;

/**
 * https://leetcode.cn/problems/longest-string-chain/
 */
public class _1048_最长回文子串 {

    public int longestStrChain(String[] words) {
        if (words == null || words.length == 0) return 0;

        // 根据words元素的length长度进行排序
        Arrays.sort(words, Comparator.comparingInt(String::length));

        // 以words[i]为结尾的最长回文子串
        int[] dp = new int[words.length];
        for (int i = 0; i < dp.length; i++) {
            dp[i] = 1;
        }

        // 赋初始值，以本身为结尾的默认值都是1
        for (int i = 0; i < words.length; i++) {
            String a = words[i];
            for (int j = i + 1; j < words.length; j++) {
                String b = words[j];
                if (isPre(a, b)) {
                    dp[j] = Math.max(dp[i] + 1, dp[j]);
                }
            }
        }

        int result = 0;
        for (int i = 0; i < dp.length; i++) {
            result = Math.max(result, dp[i]);
        }
        return result;
    }

    /**
     * 判断s1是否是s2的前身
     *
     * @param s1
     * @param s2
     * @return
     */
    private boolean isPre(String s1, String s2) {
        int m = s1.length();
        int n = s2.length();

        if (m != n - 1) return false;

        int i = 0;
        int j = 0;
        while (i < m && j < n) {
            if (s1.charAt(i) == s2.charAt(j)) {
                i++;
            }
            j++;
        }

        return i == m;
    }
}
